<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="小区" prop="areaName">
        <el-input
          v-model="queryParams.areaName"
          placeholder="请输入小区"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="缴费锁定" prop="lockSts">
        <el-select v-model="queryParams.lockSts" placeholder="请选择缴费锁定状态" clearable size="small">
          <el-option
            v-for="dict in dict.type.HOUSE001"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleMove"
        >迁移</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="areaList" height="380px" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="小区" align="center" prop="areaName" width="120"/>
      <el-table-column  :formatter="numberFormat"  label="总户数" align="center" prop="doorNumber" width="100"/>
      <el-table-column  :formatter="numberFormat"  label="总面积" align="center" prop="spaceNum" width="100"/>
      <el-table-column  :formatter="numberFormat"  label="缴费户数" align="center" prop="costNum" width="100"/>
      <el-table-column label="缴费比率" align="center" prop="costRatio" />
      <el-table-column  :formatter="numberFormat"  label="应缴金额" align="center" prop="budgetMoney" width="120"/>
      <el-table-column  :formatter="numberFormat"  label="余额" align="center" prop="costMoney" width="120"/>
      <el-table-column  :formatter="numberFormat"  label="未缴金额" align="center" prop="costMargin" width="120"/>
      <el-table-column label="锁定状态" align="center" prop="lockSts">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.HOUSE001" :value="scope.row.lockSts"/>
        </template>
      </el-table-column>
      <el-table-column label="锁定日期" align="center" prop="lockDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lockDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="creater" />
      <el-table-column label="创建时间" align="center" prop="createDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开发企业" align="center" prop="estateId" :formatter="formatterEstate"/>
      <el-table-column label="街道办事处" align="center" prop="streetId" :formatter="formatterStreet"/>
      <el-table-column label="社区" align="center" prop="communityId" :formatter="formatterCommunity"/>
      <el-table-column label="业主委员会" align="center" prop="committeeId" :formatter="formatterCommittee"/>
      <el-table-column label="物业公司" align="center" prop="propertyId" :formatter="formatterProperty"/>
      <el-table-column label="所占位置" align="center" prop="seat"/>
      <el-table-column label="建筑结构" align="center" prop="areaBuild"/>
      <el-table-column align="center" label="竣工时间" prop="areaEnd" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.areaEnd, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center"  fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            :style="{ display: scope.row.areaName=='合计'?'none':'' }"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            :style="{ display: scope.row.areaName=='合计'?'none':'' }"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改小区管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="小区" prop="areaName">
          <el-input v-model="form.areaName" placeholder="请输入小区" />
        </el-form-item>
        <el-form-item label="所占位置" prop="seat">
          <el-input v-model="form.seat" placeholder="请输入所占位置" />
        </el-form-item>
        <el-form-item label="建筑结构" prop="areaBuild">
          <el-input v-model="form.areaBuild" placeholder="请输入建筑结构" />
        </el-form-item>
        <el-form-item label="竣工时间" prop="areaEnd">
          <el-date-picker v-model="form.areaEnd"
                          placeholder="选择竣工时间" :style="{width: '100%'}"
                          type="date" value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="开发企业" prop="estateId">
          <el-select v-model="form.estateId" placeholder="请输入开发企业" clearable :style="{width: '100%'}">
            <el-option v-for="(item, index) in estateOptions" :key="index" :label="item.estateName"
              :value="item.estateId" :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="街道办事处" prop="streetId">
          <el-select v-model="form.streetId" placeholder="请输入街道办事处" clearable :style="{width: '100%'}">
            <el-option v-for="(item, index) in streetOptions" :key="index" :label="item.streetName"
              :value="item.streetId" :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="社区" prop="communityId">
          <el-select v-model="form.communityId" placeholder="请输入社区" clearable :style="{width: '100%'}">
            <el-option v-for="(item, index) in communityOptions" :key="index" :label="item.communityName"
              :value="item.communityId" :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="业主委员会" prop="tenementId">
          <el-select v-model="form.committeeId" placeholder="请输入业主委员会" clearable :style="{width: '100%'}">
            <el-option v-for="(item, index) in committeeOptions" :key="index" :label="item.committeeName"
              :value="item.committeeId" :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="物业公司" prop="propertyId">
          <el-select v-model="form.propertyId" placeholder="请输入业主委员会" clearable :style="{width: '100%'}">
            <el-option v-for="(item, index) in propertyOptions" :key="index" :label="item.propertyName"
              :value="item.propertyId" :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 迁移楼宇管理对话框 -->
    <el-dialog :title="moveTitle" :visible.sync="moveOpen" width="500px" append-to-body>
      <el-form ref="form" :model="moveForm" :rules="rules" label-width="80px">
        <el-form-item label="小区" prop="areaName">
          <el-select v-model="moveForm.areaName" :filter-method="filterMethod" placeholder="请输入小区"  filterable allow-create clearable :style="{width: '100%'}">
            <el-option v-for="(item, index) in areaIdOptions" :key="index" :label="item.areaName"
                       :value="item.areaName" :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitMoveForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listArea, getArea, delArea, addArea, updateArea ,getCommitteeId,getEstateId,getStreetId,getCommunityId,getPropertyId,moveArea} from "@/api/house/area";
import {getAreaInfo} from "@/api/house/group";

export default {
  name: "Area",
  dicts: ['HOUSE001'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 小区管理表格数据
      areaList: [],
      // 弹出层标题
      title: "",
      moveTitle: "",
      // 是否显示弹出层
      moveOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        areaName: null,
        lockSts: null,
      },
      committeeOptions:[{}],
      areaIdOptions:[{}],
      estateOptions:[{}],
      streetOptions:[{}],
      communityOptions:[{}],
      propertyOptions:[{}],
      // 表单参数
      form: {},
      moveForm: {},
      // 表单校验
      rules: {
        areaName: [
          { required: true, message: "小区不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.areaSelect();
    this.estateSelect();
    this.streetSelect();
    this.communitySelect();
    this.propertySelect();
    this.committeeSelect();
  },
  methods: {
    areaSelect(){
      getAreaInfo().then(response => {
        this.areaIdOptions = response.rows;
      });
    },
    numberFormat (row, column, cellValue) {
      cellValue += ''
      if (!cellValue.includes('.')) cellValue += '.'
      return cellValue.replace(/(\d)(?=(\d{3})+\.)/g, function ($0, $1) {
        return $1 + ','
      }).replace(/\.$/, '')
    },
    committeeSelect(){
      getCommitteeId().then(response => {
        this.committeeOptions = response.rows;
      });
    },estateSelect(){
      getEstateId().then(response => {
        this.estateOptions = response.rows;
      });
    },streetSelect(){
      getStreetId().then(response => {
        this.streetOptions = response.rows;
      });
    },communitySelect(){
      getCommunityId().then(response => {
        this.communityOptions = response.rows;
      });
    },propertySelect(){
      getPropertyId().then(response => {
        this.propertyOptions = response.rows;
      });
    },
    /** 查询小区管理列表 */
    getList() {
      this.loading = true;
      listArea(this.queryParams).then(response => {
        this.areaList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.moveOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
      this.moveForm = {};
      this.resetForm("moveForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.areaId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加小区管理";

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const areaId = row.areaId || this.ids
      getArea(areaId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改小区管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.areaId != null) {
            updateArea(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addArea(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    submitMoveForm() {
      moveArea(this.moveForm).then(response => {
        this.$modal.msgSuccess("迁移成功");
        this.moveOpen = false;
        this.getList();
      });
    },

    handleMove(row) {
      this.reset();
      const areaId = row.areaId || this.ids
      getArea(areaId).then(response => {
        this.moveForm = response.data;
        this.moveOpen = true;
        this.moveTitle = "小区迁移管理";
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const areaIds = row.areaId || this.ids;
      this.$modal.confirm('是否确认删除小区管理编号为"' + areaIds + '"的数据项？').then(function() {
        return delArea(areaIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('area/export', {
        ...this.queryParams
      }, `area_${new Date().getTime()}.xlsx`)
    },

    formatterCommittee(row, column) {
      return this.selectCommittee(this.committeeOptions, row.committeeId);
    },

    selectCommittee(datas, value) {
      var actions = [];
      Object.keys(datas).some((key) => {
        if (datas[key].committeeId == ('' + value)) {
          actions.push(datas[key].committeeName);
          return true;
        }
      })
      return actions.join('');
    },


    formatterEstate(row, column) {
          return this.selectEstate(this.estateOptions, row.estateId);
        },

    selectEstate(datas, value) {
      var actions = [];
      Object.keys(datas).some((key) => {
        if (datas[key].estateId == ('' + value)) {
          actions.push(datas[key].estateName);
          return true;
        }
      })
      return actions.join('');
    },

    formatterStreet(row, column) {
          return this.selectStreet(this.streetOptions, row.streetId);
        },

    selectStreet(datas, value) {
      var actions = [];
      Object.keys(datas).some((key) => {
        if (datas[key].streetId == ('' + value)) {
          actions.push(datas[key].streetName);
          return true;
        }
      })
      return actions.join('');
    },

    formatterCommunity(row, column) {
          return this.selectCommunity(this.communityOptions, row.communityId);
        },

    selectCommunity(datas, value) {
      var actions = [];
      Object.keys(datas).some((key) => {
        if (datas[key].communityId == ('' + value)) {
          actions.push(datas[key].communityName);
          return true;
        }
      })
      return actions.join('');
    },


    formatterProperty(row, column) {
          return this.selectProperty(this.propertyOptions, row.propertyId);
        },

    selectProperty(datas, value) {
      var actions = [];
      Object.keys(datas).some((key) => {
        if (datas[key].propertyId == ('' + value)) {
          actions.push(datas[key].propertyName);
          return true;
        }
      })
      return actions.join('');
    },






  }
};
</script>
